
import 'inapp_webview/webview_flutter_jsbridge.dart';

import 'package:flutter/material.dart';

import 'package:webview_flutter/webview_flutter.dart';
import 'package:webview_flutter_android/webview_flutter_android.dart';
import 'package:webview_flutter_wkwebview/webview_flutter_wkwebview.dart';


class EMPWebView extends StatelessWidget {
  // This widget is the root of your application.
  @override
  Widget build(BuildContext context) {
    return HomeView();
  }
}

class HomeView extends StatelessWidget {
  final jsBridge = JSBridge();

  @override
  Widget build(BuildContext context) {
    final controller = _webViewControllerSetting();

    return Scaffold(
      appBar: AppBar(
        title: Text('Flutter WebView JSBridge'),
        actions: [
          TextButton(
            onPressed: _callJS,
            child: Text(
              'callJS',
              style: TextStyle(color: Colors.white),
            ),
          ),
        ],
      ),
      body: WebViewWidget(
        controller: controller,
      ),
    );
  }

  WebViewController _webViewControllerSetting() {
    late final PlatformWebViewControllerCreationParams params;
    if (WebViewPlatform.instance is WebKitWebViewPlatform) {
      params = WebKitWebViewControllerCreationParams(
        allowsInlineMediaPlayback: true,
        mediaTypesRequiringUserAction: const <PlaybackMediaTypes>{},
      );
    } else {
      params = const PlatformWebViewControllerCreationParams();
    }

    final WebViewController webController =
    WebViewController.fromPlatformCreationParams(params);

    jsBridge.webViewController = webController;
    jsBridge.defaultHandler = _defaultHandler;
    jsBridge.registerHandler('testFlutterCallback', _nativeHandler);

    webController
      ..setJavaScriptMode(JavaScriptMode.unrestricted)
      ..setBackgroundColor(const Color(0x00000000))
      ..setNavigationDelegate(
        NavigationDelegate(
          onPageFinished: (String url) {
            print('Page finished loading: $url');
            jsBridge.injectJavascript();
          },
        ),
      )
      ..loadFlutterAsset('lib/assets/index.html');

    if (webController.platform is AndroidWebViewController) {
      AndroidWebViewController.enableDebugging(true);
      (webController.platform as AndroidWebViewController)
          .setMediaPlaybackRequiresUserGesture(false);
    }
    return webController;
  }

  Future<void> _callJS() async {
    final res = await jsBridge.callHandler('testJavascriptHandler',
        data: '_callJS from native');
    print('_callJS response: $res');
  }

  Future<Object?> _nativeHandler(Object? data) async {
    await Future.delayed(Duration(seconds: 1), () {});
    return '_nativeHandler response from native';
  }

  Future<Object?> _defaultHandler(Object? data) async {
    await Future.delayed(Duration(seconds: 1), () {});
    return '_defaultHandler response from native';
  }
}










// import 'package:flutter/cupertino.dart';
// import 'package:flutter_inappwebview/flutter_inappwebview.dart';
// import 'dart:core';
// import 'package:flutter/material.dart';
//
// class EMPWebview extends StatefulWidget {
//    EMPWebview({Key? key, required this.url}) : super(key: key);
//
//    // const EMPWebview({super.key,required this.url});
//
//    String url;
//
//    @override
//   State<EMPWebview> createState() => _WebviewState();
// }
//
// class _WebviewState extends State<EMPWebview> {
//
//
//   bool _loadPage = true;
//   InAppWebViewController? webViewController;
//
//   // GlobalKey可以获取到对应的Widget的State对象！
//   // 当我们页面内容很多时，而需要改变的内容只有很少的一部分且在树的底层的时候，我们如何去实现增量更新？
//   // 通常情况下有两种方式，第一种是通过方法的回调，去实现数据更新，第二种是通过GlobalKey，
//   final GlobalKey webViewKey = GlobalKey();
//   // webview配置
//   InAppWebViewGroupOptions options = InAppWebViewGroupOptions(
//     // 跨平台配置
//     crossPlatform: InAppWebViewOptions(
//       useShouldOverrideUrlLoading: true,
//       mediaPlaybackRequiresUserGesture: false,
//     ),
//     // android平台配置
//     android: AndroidInAppWebViewOptions(
//       //支持HybridComposition
//       useHybridComposition: true,
//     ),
//     // ios平台配置
//     ios: IOSInAppWebViewOptions(
//       allowsInlineMediaPlayback: true,
//     ),
//   );
//
//
//   @override
//   Widget build(BuildContext context) {
//     return Scaffold(appBar: AppBar(title: const Text('测试')), body: _buildbody());
//   }
//
//
//   Widget _buildbody() {
//     return Container(
//       child: InAppWebView(
//         key: webViewKey,
//         initialFile: 'https://www.baidu.com/',
//         // initialFile: 'lib/assets/html/demo.html',
//         // initialUrlRequest: URLRequest(url: Uri.parse("https://inappwebview.dev/")),
//         // initialUrlRequest: URLRequest(url: "https://www.baidu.com/"),
//         initialOptions: options,
//         // InAppWebview中获取InAppWebViewController
//         onWebViewCreated: (InAppWebViewController controller) {
//           webViewController = controller;
//           // 注册一个JS处理方法，名称为myHandlerName
//           controller.addJavaScriptHandler(
//               handlerName: 'myHandlerName',
//               callback: (args) {
//                 // 打印js方传递过来的参数
//                 print('args=js方传递过来的参数============================$args');
//                 // 传给js方的参数
//                 return "flutter给js的数据";
//               });
//         },
//         onConsoleMessage: (controller, consoleMessage) {
//           //这里是打印来自于js的conse.log打印
//           print("consoleMessage==来自于js的打印====$consoleMessage");
//         },
//         onPageCommitVisible: (inAppWebViewControlle, uri) async {
//           if (_loadPage) {
//             setState(() {
//               _loadPage = false;
//             });
//             var fileHtmlContents = await webViewController!.getHtml();
//             fileHtmlContents = fileHtmlContents!.replaceAll(
//               '<div class="flutter-view"></div>',
//               "<div class='flutter-view' style='width: 200px; height: 200px;background-color: green;'>12345678910</div>",
//             );
//             webViewController!.loadData(data: fileHtmlContents);
//           }
//         },
//       ),
//     );
//   }
// }